﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using Infragistics.WebUI.UltraWebGrid;
using uMES.LeanManufacturing.Common;
using System.IO;
using uMES.LeanManufacturing.ReportBusiness;
using uMES.LeanManufacturing.ParameterDTO;
using System.Text;
using System.Text.RegularExpressions;
using uMES.LeanManufacturing.DBUtility;
using System.Drawing;
using System.Data.OracleClient;

public partial class uMESSubmitToSecondaryWarehouseForm : ShopfloorPage
{
    const string QueryWhere = "uMESSubmitToSecondaryWarehouseForm";
    uMESCommonBusiness common = new uMESCommonBusiness();
    uMESSecondaryWarehouseBusiness bll = new uMESSecondaryWarehouseBusiness();
    uMESContainerBusiness con = new uMESContainerBusiness();
    int m_PageSize = 10;
    string businessName = "移工管理", parentName = "submittostockinfo";
    protected void Page_Load(object sender, EventArgs e)
    {
        uMESMasterPage master = this.Master as uMESMasterPage;
        master.strNavigation = "当前位置：移工任务列表";
        master.strTitle = "移工任务列表";
        master.ChangeFrame(true);
        NormalReportControl normalCntrl = new NormalReportControl();

        WebPanel = WebAsyncRefreshPanel1;
        upageTurning.PageIndexChanged += new pageTurning.PageIndexChangedEventHandler(() => { QueryData(upageTurning.CurrentPageIndex); });

        if (!IsPostBack)
        {
            //分厂最终库
            GetFactoryStock();
            ClearMessage_PageLoad();
        }
    }


    #region 数据查询

    #region 绑定分厂二级库列表
    protected void GetFactoryStock()
    {
        DataTable DT = con.GetTableInfo("factory",null,null);

        ddlFactoryStock.DataTextField = "FactoryName";
        ddlFactoryStock.DataValueField = "FactoryID";
        ddlFactoryStock.DataSource = DT;
        ddlFactoryStock.DataBind();

        ddlFactoryStock.Items.Insert(0, "");
    }
    #endregion

    #region 重置
    protected void btnReSet_Click(object sender, EventArgs e)
    {
        hdScanCon.Value = string.Empty;
        txtProductName.Text = string.Empty;
        txtStartDate.Value = "";
        txtEndDate.Value = "";
        txtContainerName.Text = string.Empty;
        txtProcessNo.Text = string.Empty;
        upageTurning.TotalRowCount = 0;
        ItemGrid.Clear();
        ClearDispData();
    }
    #endregion
    public Dictionary<string, string> GetQuery()
    {
        string strScanContainerName = txtScan.Text.Trim();
        string strProcessNo = txtProcessNo.Text.Trim();
        string strContainerName = txtContainerName.Text.Trim();
        string strProductName = txtProductName.Text.Trim();
        string strStartDate = txtStartDate.Value.Trim();
        string strEndDate = txtEndDate.Value.Trim();

        Dictionary<string, string> result = new Dictionary<string, string>();
        Dictionary<string, string> userInfo = Session["UserInfo"] as Dictionary<string, string>;
        result.Add("FactoryID", userInfo["FactoryID"]);
        if (!string.IsNullOrEmpty(hdScanCon.Value))
        {
            result.Add("ScanContainerName", hdScanCon.Value);
        }
        else
        {
            result.Add("ProcessNo", strProcessNo);
            result.Add("ContainerName", strContainerName);
            result.Add("ProductName", strProductName);
            result.Add("StartDate", strStartDate);
            result.Add("EndDate", strEndDate);
        }

        return result;
    }

    protected void txtScan_TextChanged(object sender, EventArgs e)
    {
        ClearMessage();

        try
        {
            string strScan = txtScan.Text.Trim();
            txtScan.Text = "";
            hdScanCon.Value = string.Empty;
            if (strScan != string.Empty)
            {

                hdScanCon.Value = strScan;
                QueryData(1);
            }
        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }

    //查询按钮
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        try
        {
            upageTurning.TxtCurrentPageIndex.Text = "1";
            hdScanCon.Value = string.Empty;
            QueryData(upageTurning.CurrentPageIndex);
        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }

    public void QueryData(int intIndex)
    {
        ClearMessage();

        ClearDispData();
        uMESPagingDataDTO result = bll.GetMainDataInfo(GetQuery(), intIndex, m_PageSize);
        this.ItemGrid.DataSource = result.DBTable;
        this.ItemGrid.DataBind();
        //给分页控件赋值，用于分页控件信息显示
        this.upageTurning.TotalRowCount = int.Parse(result.RowCount);
        this.upageTurning.RowCountByPage = m_PageSize;
    }

    protected void ClearDispData()
    {
        txtDispProcessNo.Text = string.Empty;
        txtDispOprNo.Text = string.Empty;
        txtDispContainerName.Text = string.Empty;
        txtContainerId.Text = string.Empty;
        txtDispProductName.Text = string.Empty;
        txtDispDescription.Text = string.Empty;
        txtProductId.Text = string.Empty;

        txtUomId.Text = string.Empty;
        txtQty.Text = string.Empty;
        txtMfgOrderName.Text = string.Empty;
        txtEmployeeId.Text = string.Empty;
        txtInEmployee.Text = string.Empty;
        try
        {
            ddlFactoryStock.SelectedIndex = 0;
        }
        catch
        {
        }

        //ItemGrid.Clear();

    }

    public void ResetQuery()
    {
        ClearMessage();

        Session[QueryWhere] = "";
        txtScan.Text = string.Empty;
        txtProcessNo.Text = string.Empty;
        txtContainerName.Text = string.Empty;
        txtProductName.Text = string.Empty;
        txtStartDate.Value = string.Empty;
        txtEndDate.Value = string.Empty;
        ItemGrid.Rows.Clear();
        upageTurning.TotalRowCount = 0;
    }
    #endregion

    #region 选中批次行
    protected void ItemGrid_ActiveRowChange(object sender, RowEventArgs e)
    {
        ClearMessage();

        try
        {
            txtDispProcessNo.Text = string.Empty;
            if (e.Row.Cells.FromKey("ProcessNo").Value != null)
            {
                string strProcessNo = e.Row.Cells.FromKey("ProcessNo").Value.ToString();
                txtDispProcessNo.Text = strProcessNo;
            }

            txtDispOprNo.Text = string.Empty;
            if (e.Row.Cells.FromKey("OprNo").Value != null)
            {
                string strOprNo = e.Row.Cells.FromKey("OprNo").Value.ToString();
                txtDispOprNo.Text = strOprNo;
            }

            string strContainerName = e.Row.Cells.FromKey("ContainerName").Value.ToString();
            txtDispContainerName.Text = strContainerName;

            string strContainerID = e.Row.Cells.FromKey("ContainerID").Value.ToString();
            txtContainerId.Text = strContainerID;

            string strProductName = e.Row.Cells.FromKey("ProductName").Value.ToString();
            txtDispProductName.Text = strProductName;

            txtDispDescription.Text = string.Empty;
            if (e.Row.Cells.FromKey("Description").Value != null)
            {
                string strDescription = e.Row.Cells.FromKey("Description").Value.ToString();
                txtDispDescription.Text = strDescription;
            }

            txtProductId.Text = string.Empty;
            if (e.Row.Cells.FromKey("productid").Value != null)
            {
                string strProductId = e.Row.Cells.FromKey("productid").Value.ToString();
                txtProductId.Text = strProductId;
            }

            txtUomId.Text = string.Empty;
            if (e.Row.Cells.FromKey("uomid").Value != null)
            {
                string strUomId = e.Row.Cells.FromKey("uomid").Value.ToString();
                txtUomId.Text = strUomId;
            }

            //批次数量
            string strQty = string.Empty;
            if (e.Row.Cells.FromKey("qty").Value != null)
            {
                strQty = e.Row.Cells.FromKey("qty").Value.ToString();
                txtQty.Text = strQty;
            }

            //显示交接人
            Dictionary<string, string> userInfo = Session["UserInfo"] as Dictionary<string, string>;
            txtInEmployee.Text = userInfo["FullName"];
            txtEmployeeId.Text = userInfo["EmployeeID"];


            //生产订单
            if (e.Row.Cells.FromKey("MfgOrderName").Value != null)
            {
                txtMfgOrderName.Text = e.Row.Cells.FromKey("MfgOrderName").Value.ToString();

            }
            //若为最终入库需要默认选择产品上的库房
            if (e.Row.Cells.FromKey("IsFinished").Text == "0")//线边库
            {
                ddlFactoryStock.Enabled = false;

            }
            else//成品库
            {
                ddlFactoryStock.Enabled = false;
                DataTable dt = con.GetTableInfo("mfgorder", "mfgordername", e.Row.Cells.FromKey("MfgOrderName").Text);
                ddlFactoryStock.SelectedValue = dt.Rows[0]["finishedtofactoryid"].ToString();
            }


        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }

    #endregion

    #region 保存按钮
    protected void btnSave_Click(object sender, EventArgs e)
    {
        // ClearMessage();

        try
        {
            Tuple<bool, string> result = SaveData();

            if (result.Item1)
            {
                ClearDispData();
                QueryData(upageTurning.CurrentPageIndex);
            }

            DisplayMessage(result.Item2, result.Item1);

        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }

    #region 数据验证
    protected Tuple<bool, string> CheckData()
    {
        Tuple<bool, string> result = new Tuple<bool, string>(true, "");

        if (txtDispContainerName.Text == "")
        {
            return new Tuple<bool, string>(false, "请选择提交入库信息");
        }

        if (ddlFactoryStock.SelectedIndex == 0)
        {

            return new Tuple<bool, string>(false, "请选择转移地点");
        }
        return result;
    }
    #endregion

    //验证是否是数字
    public bool IsNumeric(string s)
    {
        bool bReturn = true;
        double result = 0;
        try
        {
            result = double.Parse(s);
        }
        catch
        {
            result = 0;
            bReturn = false;
        }
        return bReturn;
    }

    //验证是否是正整数
    public static bool IsInt(string inString)
    {
        Regex regex = new Regex("^[0-9]*[1-9][0-9]*$");
        return regex.IsMatch(inString.Trim());
    }
    /// <summary>
    /// 保存数据
    /// </summary>
    /// <returns></returns>
    Tuple<bool, string> SaveData()
    {
        Tuple<bool, string> re = new Tuple<bool, string>(true, "");
        // re = CheckData();
        if (re.Item1 == false)
        {
            return re;
        }
        Dictionary<string, string> userInfo = Session["UserInfo"] as Dictionary<string, string>;

        // UltraGridRow activeRow = ItemGrid.DisplayLayout.ActiveRow;

        //以字典形式传递参数
        Dictionary<string, object> para = new Dictionary<string, object>();
        DataSet ds = new DataSet();
        //返回消息信息
        string strMessage = string.Empty;
        //主表要保存的信息
        DataTable dtMain = new DataTable();
        dtMain.Columns.Add("ID");//唯一标识
        dtMain.Columns.Add("ContainerID");//生产批次ID
        dtMain.Columns.Add("ProcessNo");//工作令号
        dtMain.Columns.Add("OprNo");//作业令号
        dtMain.Columns.Add("MfgOrderName");//生产订单号
        dtMain.Columns.Add("Qty");//批次数量
        dtMain.Columns.Add("ProductName");//产品/图号
        dtMain.Columns.Add("Description");//名称
        dtMain.Columns.Add("ContainerName");//生产批次号
        dtMain.Columns.Add("UOMID");//计量单位ID
        dtMain.Columns.Add("SubmitDate");//提交日期
        dtMain.Columns.Add("SubmitEmployeeID");//提交人
        dtMain.Columns.Add("SUBMITEMPLOYEE");//提交人名称
        dtMain.Columns.Add("FactoryStockID");//二级库ID
        dtMain.Columns.Add("ProductId");//产品/图号ID
        dtMain.Columns.Add("plannedstartdate");//计划开始时间
        dtMain.Columns.Add("plannedcompletiondate");//计划结束时间

        dtMain.Columns.Add("specid");//specid
        dtMain.Columns.Add("workflowid");//workflowid
        dtMain.Columns.Add("isfinished");//isfinished
        dtMain.Columns.Add("factoryid");//factoryid

        //需要更细批次状态的数据
        List<string> listCon = new List<string>();
        //日志记录对象参数
        Dictionary<string, UltraGridRow> logPara = new Dictionary<string, UltraGridRow>();
        //批量处理
        foreach (UltraGridRow activeRow in ItemGrid.Rows)
        {

            if (Convert.ToBoolean(activeRow.Cells.FromKey("ckSelect").Value) == false)
            {
                continue;
            }

            string strPlannedStartDate = string.Empty;
            if (activeRow.Cells.FromKey("plannedstartdate").Value != null)
            {
                strPlannedStartDate = activeRow.Cells.FromKey("plannedstartdate").Text;
            }

            string strPlannedCompletionDate = string.Empty;
            if (activeRow.Cells.FromKey("plannedcompletiondate").Value != null)
            {
                strPlannedCompletionDate = activeRow.Cells.FromKey("plannedcompletiondate").Text;
            }
            string isfinished = activeRow.Cells.FromKey("IsFinished").Text;


            dtMain.Rows.Add();
            int intMainRow = dtMain.Rows.Count - 1;string id = Guid.NewGuid().ToString(); logPara.Add(id, activeRow);
            dtMain.Rows[intMainRow]["ID"] = id + "㊣String"; //唯一标识
            dtMain.Rows[intMainRow]["ContainerID"] = activeRow.Cells.FromKey("ContainerID").Text + "㊣String";//生产批次ID
            dtMain.Rows[intMainRow]["ProcessNo"] = activeRow.Cells.FromKey("ProcessNo").Text + "㊣String";//工作令号
            dtMain.Rows[intMainRow]["OprNo"] = activeRow.Cells.FromKey("OprNo").Text + "㊣String";//作业令号
            dtMain.Rows[intMainRow]["MfgOrderName"] = activeRow.Cells.FromKey("MfgOrderName").Text + "㊣String";//生产订单号
            dtMain.Rows[intMainRow]["Qty"] = activeRow.Cells.FromKey("Qty").Text + "㊣Integer";//批次数量
            dtMain.Rows[intMainRow]["ProductName"] = activeRow.Cells.FromKey("ProductName").Text + "㊣String";//产品 / 图号
            dtMain.Rows[intMainRow]["Description"] = activeRow.Cells.FromKey("Description").Text + "㊣String";//名称
            dtMain.Rows[intMainRow]["ContainerName"] = activeRow.Cells.FromKey("ContainerName").Text + "㊣String";//生产批次号
            dtMain.Rows[intMainRow]["UOMID"] = activeRow.Cells.FromKey("uomid").Text + "㊣String";//计量单位ID
            if (isfinished == "1")
            {
                //DataTable dt = con.GetTableInfo("product", "productid", activeRow.Cells.FromKey("productid").Text);
                if (string.IsNullOrWhiteSpace(ddlFactoryStock.SelectedValue)) {
                    return new Tuple<bool, string>(false, "未维护最终交往地");
                }
                dtMain.Rows[intMainRow]["FactoryStockID"] = ddlFactoryStock.SelectedValue + "㊣String";//二级库ID
            }
            else
            {
                dtMain.Rows[intMainRow]["FactoryStockID"] = "";
            }

            dtMain.Rows[intMainRow]["ProductID"] = activeRow.Cells.FromKey("productid").Text + "㊣String";//产品 / 图号ID
            dtMain.Rows[intMainRow]["SubmitDate"] = DateTime.Now + "㊣Date";//提交时间
            dtMain.Rows[intMainRow]["SubmitEmployeeID"] = userInfo["EmployeeID"] + "㊣String";//交接人ID
            dtMain.Rows[intMainRow]["SubmitEmployee"] = userInfo["FullName"] + "㊣String";//交接人姓名
            dtMain.Rows[intMainRow]["plannedstartdate"] = strPlannedStartDate + "㊣Date";//计划开始时间
            dtMain.Rows[intMainRow]["plannedcompletiondate"] = strPlannedCompletionDate + "㊣Date";//计划结束时间

            dtMain.Rows[intMainRow]["specid"] = activeRow.Cells.FromKey("SpecId").Text + "㊣String";//specid
            dtMain.Rows[intMainRow]["workflowid"] = activeRow.Cells.FromKey("WorkflowId").Text + "㊣String";//workflowid
            dtMain.Rows[intMainRow]["isfinished"] = isfinished + "㊣String";//isfinished
            dtMain.Rows[intMainRow]["FactoryID"] = userInfo["FactoryID"] + "㊣String";//factoryid

            //dtMain.Rows.Add();
            //dtMain.Rows[dtMain.Rows.Count - 1]["ID"] = "" + "㊣String";           

            if (isfinished == "1")//result == true &&
            {
                listCon.Add(activeRow.Cells.FromKey("ContainerID").Text);

            }

        }
        ds.Tables.Add(dtMain);
        ds.Tables[ds.Tables.Count - 1].TableName = "SubmitToStockInfo" + "㊣ID";
        //保存数据
        para.Add("dsData", ds);
        bool result = bll.SaveDataToDatabaseNew2(para, out strMessage);

        if (result)
        {
            ContainerExcuteLog(logPara);
            foreach (string containerID in listCon)
            {

                //最终入库,保存成功后将批次信息表中的状态 修改为 2 
                DataTable dtUpdate = new DataTable();
                dtUpdate.Columns.Add("TableName");
                dtUpdate.Columns.Add("containerid");//
                dtUpdate.Columns.Add("status");//批次状态

                dtUpdate.Rows.Add();
                int intUpdateRow = dtUpdate.Rows.Count - 1;
                dtUpdate.Rows[intUpdateRow]["TableName"] = "container";
                dtUpdate.Rows[intUpdateRow]["containerid"] = containerID + "㊣String";
                dtUpdate.Rows[intUpdateRow]["status"] = "2" + "㊣String";//批次状态

                int iResult = bll.UpdateDataToDatabase(dtUpdate, out strMessage);
                if (iResult == -1)
                {
                    //DisplayMessage(strMessage, false);
                    return new Tuple<bool, string>(false, strMessage);
                }
            }
        }

        //strMessage = strMessage.Replace("\"", "").Replace("\n", "");

        strMessage = "保存成功！";
        return new Tuple<bool, string>(true, strMessage);
    }

    #endregion

    protected void btnAll_Click(object sender, EventArgs e)
    {
        uMESCommonFunction.ResetGridCheckStatus(ItemGrid, "ckSelect", 0);
    }

    protected void btnNotAll_Click(object sender, EventArgs e)
    {
        uMESCommonFunction.ResetGridCheckStatus(ItemGrid, "ckSelect", 2);
    }

    #region 批次日志记录 add:Wangjh 20210120
    void ContainerExcuteLog(Dictionary<string, UltraGridRow> para)
    {
        Dictionary<string, string> userInfo = Session["UserInfo"] as Dictionary<string, string>;
        List<MESAuditLog> entitys = new List<MESAuditLog>();
        MESAuditLog ml = new MESAuditLog();
        foreach (string key in para.Keys)
        {
            var row = para[key];
            ml = new MESAuditLog();
            ml.ContainerName = row.Cells.FromKey("ContainerName").Text; ml.ContainerID = row.Cells.FromKey("ContainerID").Text;
            ml.ParentID = key; ml.ParentName = parentName;
            ml.CreateEmployeeID = userInfo["EmployeeID"];
            ml.BusinessName = businessName; ml.OperationType = 0;
            string strMsg = "";
            if (row.Cells.FromKey("IsFinished").Text == "1")
                strMsg = ",最终入库";
            else
                strMsg = ",线边入库";

            ml.Description = "移工确认:" + row.Cells.FromKey("WorkflowStepName").Text + strMsg;

            entitys.Add(ml);

        }
        if (entitys.Count > 0)
            common.SaveMESAuditLogs(entitys);
    }
    #endregion
}